<template>
  <div class="pivot-analysis-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>高级数据透视分析</h3>
          <div class="header-actions">
            <el-button type="primary" @click="savePivotConfig">
              <el-icon><Document /></el-icon>
              保存配置
            </el-button>
            <el-button type="success" @click="loadPivotConfig">
              <el-icon><FolderOpened /></el-icon>
              加载配置
            </el-button>
            <el-button type="warning" @click="resetPivotConfig">
              <el-icon><Refresh /></el-icon>
              重置配置
            </el-button>
          </div>
        </div>
      </template>

      <el-row :gutter="20">
        <!-- 左侧配置面板 -->
        <el-col :span="8">
          <el-card class="config-panel">
            <template #header>
              <span>透视配置</span>
            </template>
            
            <!-- 数据源选择 -->
            <div class="config-section">
              <h4>数据源</h4>
              <el-select v-model="pivotConfig.dataSource" @change="handleDataSourceChange" style="width: 100%">
                <el-option label="销售数据" value="sales" />
                <el-option label="商品数据" value="products" />
                <el-option label="客户数据" value="customers" />
                <el-option label="收银员数据" value="cashiers" />
                <el-option label="支付数据" value="payments" />
              </el-select>
            </div>

            <!-- 行字段配置 -->
            <div class="config-section">
              <h4>行字段 (拖拽到此处)</h4>
              <div class="field-container">
                <div class="field-list">
                  <div 
                    v-for="field in availableFields" 
                    :key="field.key"
                    class="field-item"
                    draggable="true"
                    @dragstart="handleDragStart($event, field)"
                  >
                    <el-icon><Grid /></el-icon>
                    <span>{{ field.name }}</span>
                    <el-tag :type="getFieldTypeColor(field.type)" size="small">{{ field.type }}</el-tag>
                  </div>
                </div>
                <div 
                  class="drop-zone"
                  @drop="handleRowDrop"
                  @dragover="handleDragOver"
                  @dragenter="handleDragEnter"
                  @dragleave="handleDragLeave"
                >
                  <div v-if="pivotConfig.rowFields.length === 0" class="drop-placeholder">
                    <el-icon><Plus /></el-icon>
                    <span>拖拽字段到此处</span>
                  </div>
                  <div v-else class="field-list">
                    <div 
                      v-for="(field, index) in pivotConfig.rowFields" 
                      :key="field.key"
                      class="field-item active"
                    >
                      <el-icon><Grid /></el-icon>
                      <span>{{ field.name }}</span>
                      <el-button type="danger" size="small" @click="removeRowField(index)">
                        <el-icon><Close /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 列字段配置 -->
            <div class="config-section">
              <h4>列字段 (拖拽到此处)</h4>
              <div 
                class="drop-zone"
                @drop="handleColumnDrop"
                @dragover="handleDragOver"
                @dragenter="handleDragEnter"
                @dragleave="handleDragLeave"
              >
                <div v-if="pivotConfig.columnFields.length === 0" class="drop-placeholder">
                  <el-icon><Plus /></el-icon>
                  <span>拖拽字段到此处</span>
                </div>
                <div v-else class="field-list">
                  <div 
                    v-for="(field, index) in pivotConfig.columnFields" 
                    :key="field.key"
                    class="field-item active"
                  >
                    <el-icon><Grid /></el-icon>
                    <span>{{ field.name }}</span>
                    <el-button type="danger" size="small" @click="removeColumnField(index)">
                      <el-icon><Close /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 值字段配置 -->
            <div class="config-section">
              <h4>值字段 (拖拽到此处)</h4>
              <div 
                class="drop-zone"
                @drop="handleValueDrop"
                @dragover="handleDragOver"
                @dragenter="handleDragEnter"
                @dragleave="handleDragLeave"
              >
                <div v-if="pivotConfig.valueFields.length === 0" class="drop-placeholder">
                  <el-icon><Plus /></el-icon>
                  <span>拖拽字段到此处</span>
                </div>
                <div v-else class="field-list">
                  <div 
                    v-for="(field, index) in pivotConfig.valueFields" 
                    :key="field.key"
                    class="field-item active"
                  >
                    <el-icon><Grid /></el-icon>
                    <span>{{ field.name }}</span>
                    <el-select 
                      v-model="field.aggregation" 
                      size="small" 
                      style="width: 80px; margin: 0 5px;"
                    >
                      <el-option label="求和" value="sum" />
                      <el-option label="平均" value="avg" />
                      <el-option label="计数" value="count" />
                      <el-option label="最大" value="max" />
                      <el-option label="最小" value="min" />
                    </el-select>
                    <el-button type="danger" size="small" @click="removeValueField(index)">
                      <el-icon><Close /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 筛选条件 -->
            <div class="config-section">
              <h4>筛选条件</h4>
              <div class="filter-list">
                <div 
                  v-for="(filter, index) in pivotConfig.filters" 
                  :key="index"
                  class="filter-item"
                >
                  <el-select v-model="filter.field" placeholder="选择字段" size="small">
                    <el-option 
                      v-for="field in availableFields" 
                      :key="field.key"
                      :label="field.name"
                      :value="field.key"
                    />
                  </el-select>
                  <el-select v-model="filter.operator" placeholder="操作符" size="small">
                    <el-option label="等于" value="eq" />
                    <el-option label="不等于" value="ne" />
                    <el-option label="大于" value="gt" />
                    <el-option label="小于" value="lt" />
                    <el-option label="包含" value="contains" />
                    <el-option label="不包含" value="not_contains" />
                  </el-select>
                  <el-input v-model="filter.value" placeholder="值" size="small" />
                  <el-button type="danger" size="small" @click="removeFilter(index)">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
                <el-button type="primary" size="small" @click="addFilter">
                  <el-icon><Plus /></el-icon>
                  添加筛选
                </el-button>
              </div>
            </div>

            <!-- 生成按钮 -->
            <div class="config-actions">
              <el-button type="primary" @click="generatePivotTable" :loading="generating" size="large">
                <el-icon><Grid /></el-icon>
                生成透视表
              </el-button>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧结果面板 -->
        <el-col :span="16">
          <el-card class="result-panel">
            <template #header>
              <div class="result-header">
                <span>透视结果</span>
                <div class="result-actions">
                  <el-button type="success" @click="exportToExcel">
                    <el-icon><Download /></el-icon>
                    导出Excel
                  </el-button>
                  <el-button type="warning" @click="exportToCSV">
                    <el-icon><Download /></el-icon>
                    导出CSV
                  </el-button>
                  <el-button type="info" @click="showChartView">
                    <el-icon><TrendCharts /></el-icon>
                    图表视图
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 透视表结果 -->
            <div v-if="pivotTableData.length > 0" class="pivot-table-container">
              <div class="table-toolbar">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索数据..."
                  size="small"
                  style="width: 200px;"
                >
                  <template #prepend>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-select v-model="pageSize" size="small" style="width: 100px;">
                  <el-option label="10条/页" :value="10" />
                  <el-option label="20条/页" :value="20" />
                  <el-option label="50条/页" :value="50" />
                  <el-option label="100条/页" :value="100" />
                </el-select>
              </div>
              
              <el-table 
                :data="paginatedData" 
                border 
                stripe 
                max-height="600"
                :summary-method="getSummaries"
                show-summary
              >
                <el-table-column 
                  v-for="column in pivotTableColumns" 
                  :key="column.prop"
                  :prop="column.prop"
                  :label="column.label"
                  :width="column.width"
                  :sortable="column.sortable"
                  :formatter="column.formatter"
                />
              </el-table>
              
              <div class="pagination">
                <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="filteredData.length"
                  layout="total, sizes, prev, pager, next, jumper"
                />
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-icon size="64"><Grid /></el-icon>
              <h3>暂无数据</h3>
              <p>请配置透视字段并生成透视表</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表视图对话框 -->
    <el-dialog
      v-model="chartDialogVisible"
      title="图表视图"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="chart-dialog-content">
        <div class="chart-controls">
          <el-form inline>
            <el-form-item label="图表类型">
              <el-select v-model="chartType" @change="updateChart">
                <el-option label="柱状图" value="bar" />
                <el-option label="折线图" value="line" />
                <el-option label="饼图" value="pie" />
                <el-option label="散点图" value="scatter" />
                <el-option label="雷达图" value="radar" />
                <el-option label="面积图" value="area" />
              </el-select>
            </el-form-item>
            <el-form-item label="数据系列">
              <el-select v-model="selectedSeries" multiple @change="updateChart">
                <el-option 
                  v-for="field in pivotConfig.valueFields" 
                  :key="field.key"
                  :label="field.name"
                  :value="field.key"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="chart-container">
          <div class="chart-placeholder">
            <el-icon size="48"><TrendCharts /></el-icon>
            <p>{{ getChartTypeName(chartType) }}</p>
            <p class="chart-desc">基于透视数据生成的图表</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const generating = ref(false)
const chartDialogVisible = ref(false)
const chartType = ref('bar')
const selectedSeries = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 透视配置
const pivotConfig = reactive({
  dataSource: 'sales',
  rowFields: [],
  columnFields: [],
  valueFields: [],
  filters: []
})

// 可用字段
const availableFields = ref([
  { key: 'date', name: '日期', type: 'date' },
  { key: 'cashier', name: '收银员', type: 'string' },
  { key: 'product', name: '商品', type: 'string' },
  { key: 'category', name: '分类', type: 'string' },
  { key: 'customer', name: '客户', type: 'string' },
  { key: 'paymentMethod', name: '支付方式', type: 'string' },
  { key: 'amount', name: '金额', type: 'number' },
  { key: 'quantity', name: '数量', type: 'number' },
  { key: 'profit', name: '利润', type: 'number' },
  { key: 'orderCount', name: '订单数', type: 'number' }
])

// 透视表数据
const pivotTableData = ref([])
const pivotTableColumns = ref([])

// 拖拽相关
let draggedField = null

// 计算属性
const filteredData = computed(() => {
  if (!searchKeyword.value) return pivotTableData.value
  
  return pivotTableData.value.filter(row => {
    return Object.values(row).some(value => 
      String(value).toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  })
})

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 方法
const handleDataSourceChange = () => {
  // 根据数据源更新可用字段
  ElMessage.info(`切换到${pivotConfig.dataSource}数据源`)
}

const getFieldTypeColor = (type) => {
  const colors = {
    'date': 'primary',
    'string': 'success',
    'number': 'warning'
  }
  return colors[type] || 'info'
}

// 拖拽处理
const handleDragStart = (event, field) => {
  draggedField = field
  event.dataTransfer.effectAllowed = 'move'
}

const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

const handleDragEnter = (event) => {
  event.preventDefault()
  event.target.classList.add('drag-over')
}

const handleDragLeave = (event) => {
  event.target.classList.remove('drag-over')
}

const handleRowDrop = (event) => {
  event.preventDefault()
  event.target.classList.remove('drag-over')
  
  if (draggedField && !pivotConfig.rowFields.find(f => f.key === draggedField.key)) {
    pivotConfig.rowFields.push({ ...draggedField })
    ElMessage.success(`已添加${draggedField.name}到行字段`)
  }
  draggedField = null
}

const handleColumnDrop = (event) => {
  event.preventDefault()
  event.target.classList.remove('drag-over')
  
  if (draggedField && !pivotConfig.columnFields.find(f => f.key === draggedField.key)) {
    pivotConfig.columnFields.push({ ...draggedField })
    ElMessage.success(`已添加${draggedField.name}到列字段`)
  }
  draggedField = null
}

const handleValueDrop = (event) => {
  event.preventDefault()
  event.target.classList.remove('drag-over')
  
  if (draggedField && !pivotConfig.valueFields.find(f => f.key === draggedField.key)) {
    pivotConfig.valueFields.push({ ...draggedField, aggregation: 'sum' })
    ElMessage.success(`已添加${draggedField.name}到值字段`)
  }
  draggedField = null
}

// 字段移除
const removeRowField = (index) => {
  pivotConfig.rowFields.splice(index, 1)
}

const removeColumnField = (index) => {
  pivotConfig.columnFields.splice(index, 1)
}

const removeValueField = (index) => {
  pivotConfig.valueFields.splice(index, 1)
}

// 筛选条件
const addFilter = () => {
  pivotConfig.filters.push({
    field: '',
    operator: 'eq',
    value: ''
  })
}

const removeFilter = (index) => {
  pivotConfig.filters.splice(index, 1)
}

// 生成透视表
const generatePivotTable = async () => {
  if (pivotConfig.valueFields.length === 0) {
    ElMessage.warning('请至少添加一个值字段')
    return
  }
  
  generating.value = true
  
  // 模拟生成透视表
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  // 生成模拟数据
  generateMockPivotData()
  
  generating.value = false
  ElMessage.success('透视表生成成功')
}

const generateMockPivotData = () => {
  // 生成透视表列
  pivotTableColumns.value = [
    { prop: 'row1', label: '行字段1', width: 150, sortable: true },
    { prop: 'row2', label: '行字段2', width: 150, sortable: true },
    { prop: 'col1', label: '列字段1', width: 120, sortable: true },
    { prop: 'col2', label: '列字段2', width: 120, sortable: true },
    { prop: 'value1', label: '值字段1', width: 120, sortable: true, formatter: (row) => `¥${row.value1?.toLocaleString() || 0}` },
    { prop: 'value2', label: '值字段2', width: 120, sortable: true, formatter: (row) => row.value2?.toLocaleString() || 0 }
  ]
  
  // 生成模拟数据
  pivotTableData.value = [
    { row1: '2024-01-15', row2: '收银员001', col1: '现金', col2: '电子产品', value1: 15680.50, value2: 89 },
    { row1: '2024-01-15', row2: '收银员001', col1: '刷卡', col2: '服装', value1: 8900.00, value2: 45 },
    { row1: '2024-01-15', row2: '收银员002', col1: '现金', col2: '电子产品', value1: 12300.00, value2: 67 },
    { row1: '2024-01-15', row2: '收银员002', col1: '支付宝', col2: '食品', value1: 5600.00, value2: 23 },
    { row1: '2024-01-16', row2: '收银员001', col1: '微信', col2: '日用品', value1: 7800.00, value2: 34 },
    { row1: '2024-01-16', row2: '收银员003', col1: '现金', col2: '电子产品', value1: 18900.00, value2: 98 },
    { row1: '2024-01-16', row2: '收银员003', col1: '刷卡', col2: '服装', value1: 11200.00, value2: 56 },
    { row1: '2024-01-17', row2: '收银员001', col1: '支付宝', col2: '食品', value1: 4500.00, value2: 19 },
    { row1: '2024-01-17', row2: '收银员002', col1: '微信', col2: '日用品', value1: 6700.00, value2: 28 },
    { row1: '2024-01-17', row2: '收银员003', col1: '现金', col2: '电子产品', value1: 14200.00, value2: 72 }
  ]
}

// 表格汇总
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => Number.isNaN(value))) {
      if (column.property.includes('value1')) {
        sums[index] = `¥${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toLocaleString()}`
      } else {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toLocaleString()
      }
    } else {
      sums[index] = '-'
    }
  })
  
  return sums
}

// 图表相关
const showChartView = () => {
  if (pivotTableData.value.length === 0) {
    ElMessage.warning('请先生成透视表数据')
    return
  }
  
  selectedSeries.value = pivotConfig.valueFields.map(f => f.key)
  chartDialogVisible.value = true
}

const updateChart = () => {
  ElMessage.info(`更新图表: ${getChartTypeName(chartType.value)}`)
}

const getChartTypeName = (type) => {
  const typeNames = {
    'bar': '柱状图',
    'line': '折线图',
    'pie': '饼图',
    'scatter': '散点图',
    'radar': '雷达图',
    'area': '面积图'
  }
  return typeNames[type] || '图表'
}

// 导出功能
const exportToExcel = () => {
  ElMessage.success('Excel导出成功')
}

const exportToCSV = () => {
  ElMessage.success('CSV导出成功')
}

// 配置管理
const savePivotConfig = () => {
  const config = {
    dataSource: pivotConfig.dataSource,
    rowFields: pivotConfig.rowFields,
    columnFields: pivotConfig.columnFields,
    valueFields: pivotConfig.valueFields,
    filters: pivotConfig.filters
  }
  
  localStorage.setItem('pivotConfig', JSON.stringify(config))
  ElMessage.success('配置保存成功')
}

const loadPivotConfig = () => {
  const saved = localStorage.getItem('pivotConfig')
  if (saved) {
    const config = JSON.parse(saved)
    Object.assign(pivotConfig, config)
    ElMessage.success('配置加载成功')
  } else {
    ElMessage.warning('没有找到保存的配置')
  }
}

const resetPivotConfig = () => {
  Object.assign(pivotConfig, {
    dataSource: 'sales',
    rowFields: [],
    columnFields: [],
    valueFields: [],
    filters: []
  })
  pivotTableData.value = []
  pivotTableColumns.value = []
  ElMessage.success('配置已重置')
}

// 生命周期
onMounted(() => {
  // 初始化
})
</script>

<style scoped>
.pivot-analysis-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.config-panel {
  height: calc(100vh - 200px);
  overflow-y: auto;
}

.config-section {
  margin-bottom: 24px;
}

.config-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.field-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  background: #fafafa;
}

.field-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s ease;
}

.field-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
}

.field-item.active {
  background: #f0f9ff;
  border-color: #409eff;
}

.drop-zone {
  min-height: 60px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  padding: 12px;
  transition: all 0.3s ease;
}

.drop-zone.drag-over {
  border-color: #409eff;
  background: #f0f9ff;
}

.drop-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60px;
  color: #c0c4cc;
  font-size: 14px;
}

.drop-placeholder .el-icon {
  margin-bottom: 8px;
}

.filter-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.config-actions {
  margin-top: 24px;
  text-align: center;
}

.result-panel {
  height: calc(100vh - 200px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.pivot-table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
}

.empty-state h3 {
  margin: 16px 0 8px 0;
  color: #606266;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.chart-dialog-content {
  padding: 20px 0;
}

.chart-controls {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.chart-container {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin: 10px 0 0 0;
  font-size: 16px;
}

.chart-desc {
  font-size: 14px !important;
  color: #c0c4cc !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .el-col:first-child {
    margin-bottom: 20px;
  }
  
  .config-panel {
    height: auto;
  }
  
  .result-panel {
    height: 600px;
  }
}

@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .result-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .table-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .filter-item {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
